<template>
	<div class="sales-order-list" v-loading="loading">
		<!-- 页面标题 -->
		<div class="page-header">
			<div class="header-content">
				<h2>销售订单管理</h2>
			</div>
		</div>

		<!-- 调试信息 -->
		<div v-if="showDebugInfo" class="debug-info">
			<div class="debug-header">🔧 调试信息</div>
			<div>销售订单数据: {{ tableData.length }} 条</div>
			<div>API状态: {{ apiStatus }}</div>
			<div v-if="debugMessage">{{ debugMessage }}</div>
			<div v-if="lastError" class="error-message">❌ 最后错误: {{ lastError }}</div>
		</div>

		<!-- 操作栏 -->
		<div class="action-bar">
			<div class="left-actions">
				<el-button type="primary" @click="showCreateDialog" icon="Plus">新增</el-button>
				<el-button type="success" @click="handleExportExcel" icon="Document">导出Excel</el-button>
				<el-button type="warning" @click="handleExportPdf" icon="Printer">导出PDF</el-button>
				<el-button type="info" @click="testApi" icon="Connection">测试API</el-button>
				<el-button @click="toggleDebugInfo" type="info" size="small">
					{{ showDebugInfo ? '隐藏调试' : '显示调试' }}
				</el-button>
				<el-button @click="loadData" type="primary" size="small">
					重新加载
				</el-button>
			</div>
			<div class="right-actions">
				<el-input
					v-model="searchText"
					placeholder="请搜索"
					class="search-input"
					clearable
					@keyup.enter="handleSearch"
				>
					<template #append>
						<el-button @click="handleSearch" icon="Search" />
					</template>
				</el-input>
				<el-button @click="refreshData" icon="Refresh" />
			</div>
		</div>

		<!-- 数据表格 -->
		<el-card class="table-card" shadow="never">
			<el-table :data="tableData" border stripe v-loading="tableLoading" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column type="index" label="#" width="60" />
				<el-table-column prop="salesOrderNumber" label="订单编号" width="160" />
				<el-table-column prop="orderSubject" label="订单主题" min-width="200" show-overflow-tooltip />
				<el-table-column prop="customerName" label="客户名称" width="150" />
				<el-table-column prop="salesDate" label="订单日期" width="120">
					<template #default="{ row }">
						{{ formatDate(row.salesDate) }}
					</template>
				</el-table-column>
				<el-table-column label="物品概要" min-width="180">
					<template #default="{ row }">
						<el-tooltip :content="row.itemSummary || '无明细'" placement="top" :show-after="500">
							<span>{{ row.itemSummary || '无明细' }}</span>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column prop="totalAmount" label="总金额" width="120">
					<template #default="{ row }">
						¥{{ formatNumber(row.totalAmount) }}
					</template>
				</el-table-column>
				<el-table-column label="已收款" width="100">
					<template #default>
						¥0.00
					</template>
				</el-table-column>
				<el-table-column label="已开票金额" width="120">
					<template #default>
						¥0.00
					</template>
				</el-table-column>
				<el-table-column label="出库" width="100">
					<template #default="{ row }">
						<span>{{ row.orderStatus === '已完成' ? '已完成出库' : '未出库' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="收款" width="100">
					<template #default="{ row }">
						<span>{{ row.orderStatus === '已完成' ? '已完成收款' : '未收款' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="orderStatus" label="状态" width="100">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.orderStatus)">{{ row.orderStatus }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createName" label="创建人" width="100" />
				<el-table-column prop="createTime" label="创建时间" width="160">
					<template #default="{ row }">
						{{ formatDateTime(row.createTime) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="120" fixed="right">
					<template #default="{ row }">
						<el-button @click="viewDetail(row.id)" type="primary" link icon="View">查看</el-button>
						<el-button 
							v-if="row.orderStatus === '草稿'" 
							@click="deleteOrder(row.id)" 
							type="danger" 
							link 
							icon="Delete"
						>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="pagination-wrapper">
				<div class="pagination-info">
					共 {{ pagination.total }} 项数据，当前第 {{ pagination.pageIndex }} 页
				</div>
				<el-pagination
					v-model:current-page="pagination.pageIndex"
					v-model:page-size="pagination.pageSize"
					:page-sizes="[5, 10, 20, 50]"
					:total="pagination.total"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-card>

		<!-- 新增/编辑对话框 -->
		<el-dialog
			v-model="dialogVisible"
			:title="dialogTitle"
			width="80%"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<SalesOrderForm
				ref="formRef"
				:form-data="formData"
				:is-edit="isEdit"
				@submit="handleSubmit"
				@cancel="dialogVisible = false"
			/>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { salesOrderApi } from '@/api/salesOrderApi'
import type { SalesOrderDetailResponse, CreateSalesOrderCommand, UpdateSalesOrderCommand, GetSalesOrderListQuery, SalesOrderQueryOutput } from '@/types/salesOrder'
import SalesOrderForm from './SalesOrderForm.vue'
import * as XLSX from 'xlsx'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

const router = useRouter()
const loading = ref(false)
const tableLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

// 简单搜索文本（不参与后端过滤，仅用于前端触发刷新）
const searchText = ref('')

// 调试相关
const showDebugInfo = ref(false)
const apiStatus = ref('未连接')
const debugMessage = ref('')
const lastError = ref('')

// 分页信息
const pagination = reactive({
	pageIndex: 1,
	pageSize: 5,
	total: 0
})

// 表单数据
const formData = ref<Partial<SalesOrderDetailResponse>>({})

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑销售订单' : '新增销售订单')

// 生命周期
onMounted(() => {
	loadData()
})

// 加载数据（仅分页，无查询条件）
const loadData = async () => {
	try {
		tableLoading.value = true
		apiStatus.value = '连接中...'
		
		const query: GetSalesOrderListQuery = {
			pageIndex: pagination.pageIndex,
			pageSize: pagination.pageSize
		}

		console.log('查询参数(仅分页):', query)
		const res = await salesOrderApi.getList(query)
		console.log('API响应:', res)
		
		// 验证响应数据结构
		if (!res) {
			apiStatus.value = '响应为空'
			lastError.value = 'API响应为空'
			ElMessage.error('API响应为空')
			return
		}
		
		// 检查响应是否包含必要的字段
		if (typeof res.code === 'undefined') {
			apiStatus.value = '响应格式错误'
			lastError.value = '响应缺少code字段'
			ElMessage.error('响应格式错误：缺少code字段')
			return
		}
		
		// 检查响应是否包含分页数据
		if (typeof res.pageData === 'undefined' && typeof res.PageData === 'undefined') {
			apiStatus.value = '响应格式错误'
			lastError.value = '响应缺少pageData字段'
			ElMessage.error('响应格式错误：缺少pageData字段')
			return
		}
		
		// 检查响应是否包含总数信息
		if (typeof res.totalCount === 'undefined' && typeof res.TotalCount === 'undefined') {
			apiStatus.value = '响应格式错误'
			lastError.value = '响应缺少totalCount字段'
			ElMessage.error('响应格式错误：缺少totalCount字段')
			return
		}
		
		// 记录响应结构信息
		console.log('响应结构验证:', {
			hasCode: typeof res.code !== 'undefined',
			hasPageData: typeof res.pageData !== 'undefined' || typeof res.PageData !== 'undefined',
			hasTotalCount: typeof res.totalCount !== 'undefined' || typeof res.TotalCount !== 'undefined',
			responseKeys: Object.keys(res)
		})
		
		// 检查响应状态码
		if (res.code !== 200 && res.code !== 0) {
			apiStatus.value = 'API返回错误'
			lastError.value = res.message || `API返回错误码: ${res.code}`
			debugMessage.value = `API返回错误: ${res.message}`
			ElMessage.error(res.message || `API返回错误码: ${res.code}`)
			return
		}
		
		// 成功处理数据
		// API直接返回APIPageing类型
		const rawData = res.pageData || res.PageData || []
		console.log('原始数据:', rawData)
		console.log('分页信息:', {
			totalCount: res.totalCount || res.TotalCount,
			pageCount: res.pageCount || res.PageCount,
			pageIndex: res.pageIndex || res.PageIndex,
			pageSize: res.pageSize || res.PageSize
		})
		
		// 验证数据结构
		if (!Array.isArray(rawData)) {
			console.error('pageData不是数组:', rawData)
			apiStatus.value = '数据格式错误'
			lastError.value = '返回的数据格式不正确'
			ElMessage.error('返回的数据格式不正确')
			return
		}
		
		// 转换字段名称，兼容后端返回的大写字段名
		tableData.value = rawData.map((item: any, index: number) => {
			const converted = {
				id: item.id ?? item.Id,
				salesOrderNumber: item.salesOrderNumber ?? item.SalesOrderNumber,
				orderSubject: item.orderSubject ?? item.OrderSubject,
				customerName: item.customerName ?? item.CustomerName,
				salesDate: item.salesDate ?? item.SalesDate,
				orderStatus: item.orderStatus ?? item.OrderStatus,
				itemSummary: item.itemSummary ?? item.ItemSummary,
				totalAmount: item.totalAmount ?? item.TotalAmount,
				totalQuantity: item.totalQuantity ?? item.TotalQuantity,
				createName: item.createName ?? item.CreateName,
				createTime: item.createTime ?? item.CreateTime
			}
			console.log(`转换第${index + 1}条数据:`, { 原始: item, 转换后: converted })
			return converted
		})
		
		pagination.total = res.totalCount || res.TotalCount || 0
		apiStatus.value = '连接成功'
		debugMessage.value = `成功加载 ${tableData.value.length} 条销售订单数据`
		lastError.value = ''
		console.log('设置数据:', { tableData: tableData.value, total: pagination.total })
	} catch (error: any) {
		apiStatus.value = '连接异常'
		const msg = error.message || '未知错误'
		lastError.value = msg
		debugMessage.value = `API连接测试失败: ${msg}`
		console.error('加载数据失败:', error)
		console.error('错误详情:', {
			name: error.name,
			message: error.message,
			stack: error.stack,
			response: error.response
		})
		ElMessage.error(error.message || '获取数据失败')
	} finally {
		tableLoading.value = false
	}
}

// 搜索（仅触发刷新，不传过滤条件）
const handleSearch = () => {
	pagination.pageIndex = 1
	loadData()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
	pagination.pageSize = size
	pagination.pageIndex = 1
	loadData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
	pagination.pageIndex = page
	loadData()
}

// 选择行变化
const handleSelectionChange = (rows: any[]) => {
	selectedRows.value = rows
}

// 显示新增对话框
const showCreateDialog = () => {
	isEdit.value = false
	formData.value = {
		salesDate: new Date().toISOString().split('T')[0],
		orderStatus: '草稿',
		orderDetails: []
	}
	dialogVisible.value = true
}

// 编辑订单
const editOrder = async (id: number) => {
	try {
		const res = await salesOrderApi.getById(id)
		if (res.code === 200) {
			isEdit.value = true
			formData.value = { ...res.data }
			dialogVisible.value = true
		} else {
			ElMessage.error(res.message || '获取订单信息失败')
		}
	} catch (error: any) {
		ElMessage.error(error.message || '获取订单信息失败')
	}
}

// 查看详情
const viewDetail = (id: number) => {
	router.push(`/SalesOrderDetail/${id}`)
}

// 删除订单
const deleteOrder = async (id: number) => {
	try {
		await ElMessageBox.confirm('确定要删除这个销售订单吗？', '确认删除', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})

		const res = await salesOrderApi.delete(id)
		if (res.code === 200) {
			ElMessage.success('删除成功')
			loadData()
		} else {
			ElMessage.error(res.message || '删除失败')
		}
	} catch (error: any) {
		if (error !== 'cancel') {
			ElMessage.error(error.message || '删除失败')
		}
	}
}

// 提交表单
const handleSubmit = async (data: CreateSalesOrderCommand | UpdateSalesOrderCommand) => {
	try {
		loading.value = true
		let res

		if (isEdit.value) {
			res = await salesOrderApi.update(data as UpdateSalesOrderCommand)
		} else {
			res = await salesOrderApi.create(data as CreateSalesOrderCommand)
		}

		if (res.code === 200) {
			ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
			dialogVisible.value = false
			loadData()
		} else {
			ElMessage.error(res.message || (isEdit.value ? '更新失败' : '创建失败'))
		}
	} catch (error: any) {
		ElMessage.error(error.message || (isEdit.value ? '更新失败' : '创建失败'))
	} finally {
		loading.value = false
	}
}

// 插入测试数据
const insertTestData = async () => {
	try {
		loading.value = true
		const res = await salesOrderApi.insertTestData()
		if (res.code === 200) {
			ElMessage.success('测试数据插入成功')
			loadData()
		} else {
			ElMessage.error(res.message || '测试数据插入失败')
		}
	} catch (error: any) {
		ElMessage.error(error.message || '测试数据插入失败')
	} finally {
		loading.value = false
	}
}

// 测试API
const testApi = async () => {
	try {
		loading.value = true
		const res = await salesOrderApi.testConnection()
		if (res.code === 200) {
			ElMessage.success('API连接测试成功')
		} else {
			ElMessage.error(res.message || 'API连接测试失败')
		}
	} catch (error: any) {
		ElMessage.error(error.message || 'API连接测试失败')
	} finally {
		loading.value = false
	}
}

// 刷新数据
const refreshData = () => {
	loadData()
}

// 切换调试信息显示
const toggleDebugInfo = () => {
	showDebugInfo.value = !showDebugInfo.value
}

// 导出辅助
const normalizeRowsForExport = () => {
	const rows = selectedRows.value.length > 0 ? selectedRows.value : tableData.value
	return rows.map((r: any, idx: number) => ({
		序号: idx + 1,
		销售单号: r.salesOrderNumber || '',
		销售订单主题: r.orderSubject || '',
		客户名称: r.customerName || '',
		销售日期: r.salesDate ? new Date(r.salesDate).toLocaleDateString('zh-CN') : '',
		物品概要: r.itemSummary || '',
		总金额含税: r.totalAmount ?? 0
	}))
}

const handleExportExcel = () => {
	const data = normalizeRowsForExport()
	if (data.length === 0) {
		ElMessage.info('没有可导出的数据')
		return
	}
	const ws = XLSX.utils.json_to_sheet(data)
	const wb = XLSX.utils.book_new()
	XLSX.utils.book_append_sheet(wb, ws, '销售订单')
	const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')
	XLSX.writeFile(wb, `销售订单列表-${ts}.xlsx`)
	ElMessage.success('Excel 导出成功')
}

const handleExportPdf = async () => {
	const area = document.querySelector('.sales-order-list') as HTMLElement
	if (!area) {
		ElMessage.error('未找到可导出的区域')
		return
	}
	try {
		const canvas = await html2canvas(area, { scale: 2, useCORS: true, backgroundColor: '#ffffff' })
		const imgData = canvas.toDataURL('image/png')
		const pdf = new jsPDF('l', 'pt', 'a4')
		const pageWidth = pdf.internal.pageSize.getWidth()
		const imgWidth = pageWidth - 40
		const imgHeight = (canvas.height * imgWidth) / canvas.width
		pdf.addImage(imgData, 'PNG', 20, 20, imgWidth, imgHeight)
		pdf.setFontSize(10)
		pdf.text(`导出时间: ${new Date().toLocaleString()}`, 20, pdf.internal.pageSize.getHeight() - 10)
		const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')
		pdf.save(`销售订单列表-${ts}.pdf`)
		ElMessage.success('PDF 导出成功')
	} catch (e) {
		console.error('导出 PDF 失败', e)
		ElMessage.error('导出 PDF 失败')
	}
}

// 工具函数
const formatDate = (date: string) => {
	return date ? new Date(date).toLocaleDateString('zh-CN') : '-'
}

const formatDateTime = (date: string) => {
	return date ? new Date(date).toLocaleString('zh-CN') : '-'
}

const formatNumber = (num: number) => {
	return num ? num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '0.00'
}

const getStatusType = (status: string) => {
	switch (status) {
		case '已完成':
		case '已审批':
			return 'success'
		case '审批中':
		case '待审批':
			return 'warning'
		case '已提交':
		case '草稿':
			return 'info'
		case '驳回':
		case '已取消':
			return 'danger'
		default:
			return 'info'
	}
}
</script>

<style scoped>
.sales-order-list {
	padding: 20px;
}

.page-header {
	margin-bottom: 16px;
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.header-content h2 {
	margin: 0;
}

.action-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
	padding: 16px;
	background: #f5f7fa;
	border-radius: 4px;
}

.left-actions {
	display: flex;
	gap: 10px;
}

.right-actions {
	display: flex;
	align-items: center;
	gap: 10px;
}

.search-input {
	width: 300px;
}

.table-card {
	margin-bottom: 16px;
}

.pagination-wrapper {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: 20px;
}

.pagination-info {
	color: #606266;
	font-size: 14px;
}

.status-change-content {
	text-align: center;
}

.text-warning {
	color: #e6a23c;
	font-weight: bold;
}

.dialog-footer {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
}

:deep(.el-form--inline .el-form-item) {
	margin-right: 16px;
	margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.sales-order-list {
		padding: 10px;
	}
	
	.action-bar {
		flex-direction: column;
		gap: 15px;
		align-items: stretch;
	}
	
	.left-actions,
	.right-actions {
		justify-content: center;
	}
	
	.right-actions .search-input {
		width: 100% !important;
	}
}

/* 调试信息样式 */
.debug-info {
	background: #f0f9ff;
	border: 1px solid #0ea5e9;
	padding: 15px;
	margin-bottom: 20px;
	border-radius: 8px;
	font-size: 14px;
}

.debug-header {
	color: #0369a1;
	font-weight: bold;
	margin-bottom: 10px;
}

.error-message {
	color: #dc2626;
	margin-top: 5px;
}
</style> 